package samples.barcode;


import javax.swing.ImageIcon;

import org.dom4j.Element;
import org.dom4j.XPathException;

import br.cin.ufpe.in1118.middleware.distribution.message.SOAPFactory;
import br.cin.ufpe.in1118.middleware.distribution.services.util.MiddlewareUtil;
import br.cin.ufpe.in1118.middleware.exceptions.RemoteException;
import br.cin.ufpe.in1118.middleware.internal.Base64;

public final class Barcode_SF extends SOAPFactory {

	@Override
	public Object fromSOAP(String operation, String soapMessage) throws RemoteException {
		Element rootElement = null;
		try {
			rootElement = createRootElement(soapMessage);

			Element response = (Element) rootElement.selectSingleNode("//doBarCodesResponse");
			if (response != null) {
				Element bytes = response.element("soapVal");
				byte[] bs = bytes.getText().getBytes();
				ImageIcon icon = new ImageIcon(Base64.decode(bs));
				return icon;
			}
		} catch (XPathException e) {
			Element elem = (Element) rootElement.selectSingleNode("//faultstring");
			throw new RemoteException(elem.getText());
		} catch (Exception e) {
			MiddlewareUtil.encapsulateException(e);
		}
		return null;
	}

	@Override
	public String toSOAP(String operation, Object... parameters) {
		String body = "<tns:doBarCodes xmlns:tns=\"urn:BarCodes\" xmlns:types=\"urn:BarCodes/encodedTypes\">" +
		"<username xsi:type=\"xsd:string\">any</username>" +
		"<password xsi:type=\"xsd:string\">any</password>" +
		"<num xsi:type=\"xsd:string\">" + parameters[0] + "</num>" +
		"<imgtype xsi:type=\"xsd:string\">png</imgtype>" +
		"</tns:doBarCodes>";

		return String.format("%s\n%s\n%s\n%s\n%s\n%s\n",
				TEMPLATE_XML_DECLARATION,
				TEMPLATE_HEADER_ENV,
				TEMPLATE_HEADER_BODY,
				body,
				TEMPLATE_TAIL_BODY,
				TEMPLATE_TAIL_ENV);
	}

}
